import { dbclickMenuTreeItemAfterCreate } from '@renderer/utils/dom'
import { fileTreeIndexeddbStorage } from '@renderer/store/fileTreeIndexeddb'
import { setRenamingMenuItemIdToLocal } from '@renderer/store/localstorage'
import useCurrentFile from '../useCurrentFile'
import useFileTree from '@renderer/hooks/useFileTree'
import useOpenKeys from '../useOpenKeys'
import useTabJsonModel from '../useTabJsonModel'
import { watchEffect } from 'vue'

export default function useAddFile() {
  console.log('useAddFile')
  const { getFileTree } = useFileTree()
  const { updateCurrentFile } = useCurrentFile()
  const { addOpenKeys } = useOpenKeys()
  const { updateTabJsonModelWhenCurrentFileChanged } = useTabJsonModel()

  const addFile = watchEffect(async (name, type, tabModel, parentId, fileData) => {
    if (!tabModel) return

    const file = await fileTreeIndexeddbStorage.addFile(name, type, parentId, fileData)

    if (parentId) {
      addOpenKeys([parentId])
    }
    setRenamingMenuItemIdToLocal(file.id)

    getFileTree()

    dbclickMenuTreeItemAfterCreate()

    updateCurrentFile(file)

    updateTabJsonModelWhenCurrentFileChanged(file, tabModel)
    console.log(file, 'addFile');
    return file
  })

  return { addFile }
}
